from django.conf.urls.defaults import *
from cookbook.views import *

from django.contrib.auth.views import login, logout
from MacGyver.cookbook.models import Recipie
from MacGyver.cookbook.models import Category
from django.contrib.auth.models import User
from django.contrib import admin


from django.conf import settings

admin.autodiscover()

urlpatterns = patterns('', 
	('^$', index),
	(r'^admin/', include(admin.site.urls)),
	(r'^accounts/register',  register),
	(r'^accounts/logout/$', logout),
	(r'^accounts/',  login),
	(r'^recipie/(\d+)/$', recipie_details ),
	(r'^recipie', recipie ),
	(r'^search/$', search_recipie),
	(r'^about/$', about), 
	(r'^web_client/(?P<path>.*)$', 'django.views.static.serve',
	{'document_root': settings.STATIC_DOC_ROOT})

)

#rest part

from django_restapi.resource import Resource
from django.shortcuts import render_to_response
from django.http import Http404, HttpResponse
from cookbook.models import Item, Category, delete_recipie, delete_category, create_category,  create_recepie, update_recepie, create_item, delete_item, update_item
from django_restapi.authentication import HttpBasicAuthentication

	
class Recipies(Resource):
	"""
	Resource for retriving recipie list and adding a single recipie
	"""	
	def read(self, request):
		try:
			list = Recipie.objects.all()
		except Recipie.DoesNotExist:
			raise Http404
		return render_to_response('json/list.json', {'list': list, }, mimetype="application/json")
		
	def create(self, request):
		import simplejson as json
		try:
			requestJson = json.loads(request.raw_post_data)
		except ValueError:
			raise Http404
		
		ime = requestJson['name']
		kategorije = requestJson['categories']
		stavke = requestJson['items']
		opis = requestJson['description']
		create_recepie(name=ime, categories=kategorije, items=stavke, description=opis)
		return HttpResponse(status=200)
		
class SingleRecipie(Resource):
	"""
	Resource for handling recepies
	"""
	def delete(self, request, id):
		delete_recipie(id)
		return HttpResponse(status=200)
		
	def read(self, request, id):
		try:
			recipie = Recipie.objects.get(id = id)
		except Recipie.DoesNotExist:
			raise Http404
		return render_to_response('json/recepie.json', {'recipie':recipie, }, mimetype="application/json")
	
	def update(self, request, id):
		import simplejson as json
		try:
			requestJson = json.loads(request.raw_post_data)
		except ValueError:
			raise Http404
		ime = requestJson['name']
		kategorije = requestJson['categories']
		stavke = requestJson['items']
		opis = requestJson['description']
		try:
			update_recepie(id = id, name=ime, categories=kategorije, items=stavke, description=opis)
		except ValueError:
			raise Http404
		return HttpResponse(status=200)
		
class Items(Resource):
	"""
	Resource for retriving item list and adding a single item
	"""	
	def read(self, request):
		try:
			list = Item.objects.all()
		except Item.DoesNotExist:
			raise Http404
		return render_to_response('json/list.json', {'list': list, }, mimetype="application/json")
		
	def create(self, request):
		import simplejson as json
		try:
			requestJson = json.loads(request.raw_post_data)
		except ValueError:
			raise Http404
		
		ime = requestJson['name']
		create_item(name=ime)
		return HttpResponse(status=200)
		
class SingleItem(Resource):
	"""
	Resource for handling items
	"""
	def read(self, request, id):
		try:
			item = Item.objects.get(id = id)
		except Item.DoesNotExist:
			raise Http404
		return render_to_response('json/single.json', {'single':item, }, mimetype="application/json")

	def delete(self, request, id):
		delete_item(id)
		return HttpResponse(status=200)
	
	def update(self, request, id):
		import simplejson as json
		try:
			requestJson = json.loads(request.raw_post_data)
		except ValueError:
			raise Http404
		ime = requestJson['name']
		update_item(id=id, name=ime)
		return HttpResponse(status=200)
		
class Categories(Resource):
	"""
	Resource for retriving category list and adding a single category
	"""
	def read(self, request):
		try:
			list = Category.objects.all()
		except Category.DoesNotExist:
			raise Http404
		return render_to_response('json/list.json', {'list': list, }, mimetype="application/json")
		
	def create(self, request):
		import simplejson as json
		try:
			requestJson = json.loads(request.raw_post_data)
		except ValueError:
			raise Http404
		categoryName = requestJson["name"]
		create_category(name=categoryName)

		return HttpResponse(status=200)

class SingleCategory(Resource):
	"""
	Resource for handling categories
	"""
	def read(self, request, id):
		try:
			category = Category.objects.get(id = id)
		except Category.DoesNotExist:
			raise Http404
		return render_to_response('json/single.json', {'single':category, }, mimetype="application/json")

	def delete(self, request, id):
		delete_category(id)
		return HttpResponse(status=200)
	
	def update(self, request, id):
		import simplejson as json
		try:
			requestJson = json.loads(request.raw_post_data)
		except ValueError:
			raise Http404
		ime = requestJson['name']
		
		try:
			kategorija = Category.objects.get(id = id)
			kategorija.name = ime
			kategorija.save()
		except ValueError:
			raise Http404
		return HttpResponse(status=200)
		
		
		
class RegisterUser(Resource):
	"""
	Resource for handling user registration
	"""
	def create(self, request):
		import simplejson as json
		try:
			requestJson = json.loads(request.raw_post_data)
			
		except ValueError:
			raise Http404
		usernm = requestJson['username']
		passwd = requestJson['password']
		if User.objects.get(username = usernm):
			#existing user - conflict
			return HttpResponse(status=409)
		user = User.objects.create_user(username=usernm, email='somemail@some.where', password=passwd)
		
		return HttpResponse(status=200)
		
class RecipieSearch(Resource):
	def create(self, request):
		import simplejson as json
		try:
			requestJson = json.loads(request.raw_post_data)
		except ValueError:
			raise Http404
		found = findRecipies(requestJson['id'])
		return render_to_response('json/list.json', {'list': found, }, mimetype="application/json")


def findRecipies(ids):
	
	recipieList = []
	idsInt = []
	
	for ID in ids: idsInt.append(int(ID)) 

	item_list = Item.objects.all()
	all_recipies = Recipie.objects.all()

	for recept in all_recipies:
		match = True
		for item in recept.items.all():
			if idsInt.count(item.id) == 0 : match = False
		if match: recipieList.append(recept)

	return recipieList

		
urlpatterns += patterns( '',  
    url(r'^json/recipie/$', Recipies( permitted_methods=('GET', 'POST') ) ), 
    url(r'^json/recipie/(?P<id>\d+)/$', SingleRecipie( permitted_methods=('GET', 'PUT' ,'DELETE')) ), 
    url(r'^json/item/$', Items( permitted_methods=('GET', 'POST') ) ),
    url(r'^json/item/(?P<id>\d+)/$', SingleItem( permitted_methods=( 'GET', 'PUT' ,'DELETE') ) ),
    url(r'^json/category/$', Categories( permitted_methods=('GET', 'POST') ) ),
    url(r'^json/category/(?P<id>\d+)/$', SingleCategory( permitted_methods=( 'GET', 'PUT', 'DELETE') ) ),
    url(r'^json/registerUser/$', RegisterUser( permitted_methods=('POST',) ) ),
    url(r'^json/recipieSearch/$', RecipieSearch( permitted_methods=('POST',), authentication = HttpBasicAuthentication() ) ),
)
